package cn.jofei.server.http.controller;

import cn.jofei.common.ano.ServerLet;
import cn.jofei.common.enums.Headers;
import cn.jofei.common.enums.MediaType;
import cn.jofei.common.util.Resource;
import cn.jofei.server.http.entity.R;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 公共请求
 *
 * @author Jofei Bao
 * @version ngbao v1.0.2
 * @date 2022年07月10日 23:26
 */
@ServerLet(path = "common")
public class CommonController {
    /**
     * 获取用户远程ip
     *
     * @param params
     * @param request
     * @return
     */
    @ServerLet(path = "getIp")
    public R<String> getIp(Map<String, String> params, HttpRequest request) {
        return R.success(request.headers().get(Headers.X_Real_IP));
    }

    @ServerLet(path = "img")
    public HttpResponse img(Map<String, String> params, HttpRequest request) {
        String name = "classpath:img/" + params.get("name");
        byte[] bytes = Resource.readToByte(name);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
        response.headers()
                .add(Headers.Date, LocalDateTime.now().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME))
                .add(Headers.CONTENT_TYPE, MediaType.IMG)
                .add(Headers.Content_Length, bytes.length + "");
        response.content().writeBytes(bytes);
        return response;
    }
}
